<template>
  <div class="chat-container">
    <h1>在线问答系统</h1>
    <div class="chat-box" ref="chatBox">
      <div
        class="message user-message"
        v-for="(message, index) in messages"
        :key="index"
        :class="{
          'user-message': message.type === 'user',
          'bot-message': message.type === 'bot',
        }"
      >
        {{ message.text }}
      </div>
    </div>
    <div class="input-container">
      <input
        v-model="question"
        type="text"
        placeholder="请输入您的问题"
        @keyup.enter="answerQuestion"
      />
      <button
        @click="answerQuestion"
        style="height: 44px; text-align: center; line-height: 44px"
      >
        提交
      </button>
    </div>
  </div>
</template>
  
  <script>
import axios from "axios";
export default {
  data() {
    return {
      question: "",
      messages: [],
      qnaPairs: [],
      index: 0,
      intervalId: null,
    };
  },
  methods: {
    // 获取后端数据
    async fetchQnAData() {
      try {
        const response = await axios.get("http://localhost:3000/api/qna");
        // console.log("本地存储的数据格式,", this.qnaPairs);
        this.qnaPairs = response.data;
        // console.log("获取的后端数据,", response.data);
        console.log("转存后的数据格式,", this.qnaPairs);
      } catch (error) {
        console.error("Failed to load Q&A data:", error);
      }
    },
    answerQuestion() {
      //   console.log(
      //     "初始化时的聊天框的scrollTop是===》",
      //     this.$refs.chatBox.scrollTop
      //   );
      //   console.log(
      //     "初始化时的聊天框的scrollHeight是===》",
      //     this.$refs.chatBox.scrollHeight
      //   );
      if (this.question.trim() === "") {
        alert("请输入问题");
        return;
      }

      console.log("用户输入的语句", this.question);
      this.messages.push({ type: "user", text: this.question });
      this.question = "";

      // 确保进行匹配的问题是最新提交的。
      let newestQs = this.messages[this.messages.length - 1].text;
      const qnaPair = this.qnaPairs.find(
        (pair) => pair.question.includes(newestQs)
        // (pair) => pair.question === this.messages[this.messages.length - 1].text
      );

      if (qnaPair) {
        this.messages.push({ type: "bot", text: "" });
        this.index = 0;
        this.startTypingEffect(qnaPair.answer);
      } else {
        this.messages.push({
          type: "bot",
          text: "没有找到对应的问题，请输入正确的问题。",
        });
      }

      // 这句是针对用户输入
      // 自动滚动到最新消息
      console.log("当前聊天框的scrollTop是===》", this.$refs.chatBox.scrollTop);
      console.log(
        "当前聊天框的scrollHeight是===》",
        this.$refs.chatBox.scrollHeight
      );
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    },
    startTypingEffect(answer) {
      this.intervalId = setInterval(() => {
        if (this.index < answer.length) {
          this.messages[this.messages.length - 1].text += answer[this.index];
          this.index++;
        } else {
          clearInterval(this.intervalId);
          console.log("本次任务执行结束");
        }
      }, 50);
      // 这句是针对系统给出的问题
      // 逐字打印结束后，自动滚动到最新消息
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    },
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
  created() {
    this.fetchQnAData();
  },
};
</script>
  
  <style scoped>
.chat-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

h1 {
  font-size: 24px;
  margin-bottom: 20px;
  text-align: center;
}

.chat-box {
  height: 300px;
  overflow-y: scroll;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.message {
  margin: 10px 0;
  padding: 10px;
  border-radius: 8px;
  max-width: 70%;
  word-wrap: break-word;
}

.user-message {
  background-color: #d4e6f1;
  align-self: flex-end;
  /* 用户的语句放在聊天框的右侧 */
}

.bot-message {
  background-color: #e6f1d4;
  align-self: flex-start;
  /* 系统给出的语句放在聊天框的左侧 */
}

.input-container {
  display: flex;
  justify-content: space-between;
}

input {
  flex: 1;
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
  font-size: 16px;
}

button {
  font-size: 16px;
  cursor: pointer;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 8px;
}
</style>